#include <iostream>
#include <cassert>
using namespace std;
template <class T>
class Stack {
	struct ListNode {
		T data;
		ListNode* next;
	};
	ListNode* m_list;
	int m_size;
public:
	Stack() {
		m_list = new ListNode;
		m_list->next = nullptr;
		m_size = 0;
	}
	Stack(T data) : Stack() { // 委托构造
		ListNode* node = new ListNode;
		node->data = data;
		node->next = nullptr;
		m_list->next = node;
		m_size++;
	}
	~Stack() {
		ListNode* it = m_list;
		ListNode* pr = nullptr;
		while (it) {
			pr = it;
			it = it->next;
			delete pr;
		}
		m_list = nullptr;
		m_size = -1;
	}
public:
	void push(T data) {	// 入栈
		ListNode* node = new ListNode;
		node->data = data;
		node->next = m_list->next;
		m_list->next = node;
		m_size++;
	}
	void pop() { // 出栈
		ListNode* del = m_list->next;
		m_list->next = del->next;
		delete del;
		m_size--;
	}
	void clear() { // 清空栈内元素
		ListNode* it = m_list->next;
		ListNode* pr = nullptr;
		while (it) {
			pr = it;
			it = it->next;
			delete pr;
		}
		m_list->next = nullptr; // 记得设为空指针
		m_size = 0;
	}
public:
	bool empty() {
		return m_list->next == nullptr;
	}
	int size() {
		return m_size;
	}
	T getTop() { // 获取栈顶元素
		return m_list->next->data;
	}
	T operator[](int pos) { // 使用值传递，不能修改内部值
		assert(pos >= 0 && pos < m_size);
		ListNode* current = m_list->next;
		while (pos--) {
			current = current->next;
		}
		return current->data;
	}
};
int main() {
	Stack<int> stack(1);
	stack.push(2);
	stack.push(3);
	stack.push(4);
	stack.push(5);
	stack.push(6);
	stack.clear();
	for (int i = 0; i < stack.size(); ++i) {
		cout << stack[i] << " ";
	}
	return 0;
}